package com.xincheng.shuimalong.activity.bank;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.request.RequestOptions;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.holder.RecyclerHolder;
import com.xincheng.library.xswipemenurecyclerview.listener.OnItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.listener.OnSwipeMenuItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.recycler.SwipeMenuRecyclerView;
import com.xincheng.library.xswipemenurecyclerview.swipe.Closeable;
import com.xincheng.library.xswipemenurecyclerview.swipe.DirectionMode;
import com.xincheng.library.xswipemenurecyclerview.swipe.SwipeMenu;
import com.xincheng.library.xswipemenurecyclerview.swipe.SwipeMenuCreator;
import com.xincheng.library.xswipemenurecyclerview.swipe.SwipeMenuItem;
import com.xincheng.library.xswipemenurecyclerview.widget.DividerListItemDecoration;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.adapter.BankCardAdapter;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.bank.BankCard;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Created by 许浩 on 2017/6/20.
 */

public class MyBankCardActivity extends BaseActivity {
    @BindView(R.id.bankcard_rv)
    SwipeMenuRecyclerView mBankcardRv;

    private BankCardAdapter mAdapter;
    private String mToken;
    private int mFrom;
    private BankCard.Data mCurrentBankData;

    private SwipeMenuCreator mMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.item_width);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext())
                    .setBackgroundDrawable(R.color.red_delete)
                    .setText(getString(R.string.delete)) // 文字，还可以设置文字颜色，大小等。。
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);
        }
    };

    @Override
    public int getLayoutResId() {
        return R.layout.activity_bankcard;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.bankcard_my));
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            mFrom = extras.getInt(IntentKey.FROM, 1);
        }
        mBankcardRv.setLayoutManager(new LinearLayoutManager(this));
        mBankcardRv.addItemDecoration(new DividerListItemDecoration(this));
        mBankcardRv.setSwipeMenuCreator(mMenuCreator);
        mAdapter = new BankCardAdapter();
        mBankcardRv.setAdapter(mAdapter);
        getBank();
    }

    @OnClick(R.id.bankcard_add_btn)
    public void bankcardAdd() {
        ShowActivity.showActivityForResult(this, BankCardAddActivity.class, RequestCodeKey.GO_ADD_BANKCARD);
    }

    @Override
    public void addListener() {
        mBankcardRv.setOnItemClickListener(new MyOnItemClickListener(this));
        mBankcardRv.setOnSwipeMenuItemClickListener(new MyOnSwipeMenuItemClickListener(this));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_ADD_BANKCARD:
                    boolean flag = data.getBooleanExtra(IntentKey.SUCCESS, false);
                    if (flag) {
                        getBank();
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class MyOnItemClickListener implements OnItemClickListener {
        private Context context;

        public MyOnItemClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onItemClick(RecyclerHolder holder, View view, int position) {
            if (mFrom == 1) {
                mCurrentBankData = mAdapter.getItem(position);
                if (mCurrentBankData.isDefault()) {
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.BANK_CARD, mCurrentBankData);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    showDeafaultAlert();
                }
            }
        }

        private void showDeafaultAlert() {
            AlertView alertView = new AlertView(context, null, getString(R.string.bankcard_default_msg),
                    getString(R.string.cancel), new String[]{getString(R.string.confirm)}, null,
                    AlertView.Style.Alert, new OnAlertItemClickListener() {
                @Override
                public void onItemClick(AlertView alertView, int position) {
                    switch (position) {
                        case 0:
                            setDefaultBank();
                            break;
                    }
                }
            });
            alertView.show();
        }
    }

    private void setDefaultBank() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.SET_DEFAULT_BANK,
                PostParam.setDefalutBank(mToken, mCurrentBankData.getId()),
                new BaseObserver(this, getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast(msg);
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.BANK_CARD, mCurrentBankData);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

    private void getBank() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.getBank(mToken),
                new BaseObserver(this, getString(R.string.loading_data)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            BankCard bankCard = GsonUtil.parseData(data, BankCard.class);
                            List<BankCard.Data> dataList = bankCard.getBankList();
                            if (!CommonUtil.isEmpty(dataList)) {
                                mAdapter.refreshData(dataList);
                            }
                        }
                    }
                });
    }

    private class MyOnSwipeMenuItemClickListener implements OnSwipeMenuItemClickListener {
        private Context context;

        public MyOnSwipeMenuItemClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition,
                                @DirectionMode int direction) {
            BankCard.Data bankCard = mAdapter.getItem(adapterPosition);
            switch (menuPosition) {
                case 0:
                    deleteBankCard(adapterPosition, bankCard);
                    break;
            }
        }

        private void deleteBankCard(final int position, BankCard.Data bankCard) {
            RetroSubscrube.getInstance().postSubscrube(AppUrl.DEL_BANK,
                    PostParam.delBankcard(mToken, bankCard.getId()),
                    new BaseObserver(context, getString(R.string.loading_data)) {
                        @Override
                        protected void onHandleSuccess(Object data, String msg) {
                            showToast(msg);
                            mAdapter.removeData(position);
                        }
                    });
        }
    }

}
